package com.xinghai.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xinghai.common.annotation.DataScope;
import com.xinghai.common.utils.DateUtils;
import com.xinghai.common.utils.StringUtils;
import com.xinghai.system.domain.XhCarInfo;
import com.xinghai.system.domain.XhVehicleOrderInfo;
import com.xinghai.system.domain.dto.XhCarInfoDTO;
import com.xinghai.system.mapper.XhCarInfoMapper;
import com.xinghai.system.mapper.XhVehicleOrderInfoMapper;
import com.xinghai.system.service.IXhCarInfoService;
import com.xinghai.system.util.XHConstant;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.List;

import static com.xinghai.common.utils.SecurityUtils.getDeptId;
import static com.xinghai.common.utils.SecurityUtils.getUsername;

/**
 * 车辆信息Service业务层处理
 * 
 * @author smy
 * @date 2024-07-21
 */
@Service
public class XhCarInfoServiceImpl extends ServiceImpl<XhCarInfoMapper, XhCarInfo> implements IXhCarInfoService
{
    @Autowired
    private XhCarInfoMapper xhCarInfoMapper;

    @Autowired
    private SqlSessionFactory sqlSessionFactory;

    @Autowired
    private XhVehicleOrderInfoMapper xhVehicleOrderInfoMapper;

    /**
     * 查询车辆信息
     * 
     * @param id 车辆信息主键
     * @return 车辆信息
     */
    @Override
    public XhCarInfo getInfo(Long id)
    {
        return xhCarInfoMapper.getInfo(id);
    }

    /**
     * 查询车辆信息列表
     * 
     * @param xhCarInfo 车辆信息
     * @return 车辆信息
     */
    @Override
    public List<XhCarInfoDTO> list(XhCarInfo xhCarInfo)
    {
        //查询车辆数据
        xhCarInfo.setDelFlag("0");
        List<XhCarInfoDTO> list = xhCarInfoMapper.list(xhCarInfo);
        return list;
    }
    @Override
    @DataScope(deptAlias = "d", userAlias = "u")
    public List<XhCarInfoDTO> allList(XhCarInfo xhCarInfo)
    {
        xhCarInfo.setDelFlag("0");
        List<XhCarInfoDTO> list = xhCarInfoMapper.allList(xhCarInfo);
        return list;
    }

    /**
     * 新增车辆信息
     * 
     * @param xhCarInfo 车辆信息
     * @return 结果
     */
    @Override
    public int insert(XhCarInfo xhCarInfo) throws Exception {
        xhCarInfo.setDeptId(getDeptId());
        //校验车牌
        if (this.lambdaQuery().eq(XhCarInfo::getCarNo,xhCarInfo.getCarNo()).eq(XhCarInfo::getDeptId,xhCarInfo.getDeptId()).eq(XhCarInfo::getDelFlag, XHConstant.DEL_FLAG_NORMAL).count() > 0){
            throw new Exception(StringUtils.format("车牌号({})已录入，不允许重复。 ",xhCarInfo.getCarNo()));
        }
        //校验行驶证
        if (this.lambdaQuery().eq(XhCarInfo::getCarLicenseNo,xhCarInfo.getCarLicenseNo()).eq(XhCarInfo::getDeptId,xhCarInfo.getDeptId()).eq(XhCarInfo::getDelFlag, XHConstant.DEL_FLAG_NORMAL).count() > 0){
            throw new Exception(StringUtils.format("行驶证号({})已录入，不允许重复。 ",xhCarInfo.getCarLicenseNo()));
        }
        xhCarInfo.setCreateBy(getUsername());
        xhCarInfo.setCreateTime(DateUtils.getNowDate());
        return xhCarInfoMapper.insert(xhCarInfo);
    }
    /**
     * 批量新增车辆信息
     *
     * @param xhCarInfoList 车辆信息
     * @return 结果
     */
    @Override
    public int insertBatch(List<XhCarInfo> xhCarInfoList)
    {
        return xhCarInfoMapper.insertBatch(xhCarInfoList);
    }
    /**
     * 修改车辆信息
     * 
     * @param xhCarInfo 车辆信息
     * @return 结果
     */
    @Override
    public int update(XhCarInfo xhCarInfo) throws Exception {
        //校验车牌
        if (this.lambdaQuery().ne(XhCarInfo::getId,xhCarInfo.getId())
                .eq(XhCarInfo::getCarNo,xhCarInfo.getCarNo())
                .eq(XhCarInfo::getDeptId,getDeptId())
                .eq(XhCarInfo::getDelFlag, XHConstant.DEL_FLAG_NORMAL).count() > 0){
            throw new Exception(StringUtils.format("车牌号({})已录入，不允许重复。 ",xhCarInfo.getCarNo()));
        }
        //校验行驶证
        if (this.lambdaQuery().ne(XhCarInfo::getId,xhCarInfo.getId())
                .eq(XhCarInfo::getCarLicenseNo,xhCarInfo.getCarLicenseNo())
                .eq(XhCarInfo::getDeptId,getDeptId())
                .eq(XhCarInfo::getDelFlag, XHConstant.DEL_FLAG_NORMAL).count() > 0){
            throw new Exception(StringUtils.format("行驶证号({})已录入，不允许重复。 ",xhCarInfo.getCarLicenseNo()));
        }
        xhCarInfo.setUpdateTime(DateUtils.getNowDate());
        return xhCarInfoMapper.update(xhCarInfo);
    }

    /**
     * 批量删除车辆信息
     * 
     * @param ids 需要删除的车辆信息主键
     * @return 结果
     */
    @Override
    public int deleteBatch(Long[] ids) throws Exception {
        if (ids.length == 1){
            //单一删除
            this.delete(ids[0]);
        }

        int i = 0;
        for (Long id : ids){
            //校验是否关联订单
            LambdaQueryWrapper<XhVehicleOrderInfo> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(XhVehicleOrderInfo::getCarId,id);
            if (xhVehicleOrderInfoMapper.selectCount(queryWrapper) > 0){
                continue;
            }
            xhCarInfoMapper.deleteBatch(ids);
            i++;
        }
        return i;
    }

    /**
     * 删除车辆信息信息
     * 
     * @param id 车辆信息主键
     * @return 结果
     */
    @Override
    public int delete(Long id) throws Exception {
        //校验是否关联订单
        LambdaQueryWrapper<XhVehicleOrderInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(XhVehicleOrderInfo::getCarId,id);
        if (xhVehicleOrderInfoMapper.selectCount(queryWrapper) > 0){
            throw new Exception("当前车辆存在关联物流订单不允许删除");
        }
        return xhCarInfoMapper.delete(id);
    }

    /**
     * 导入车辆信息信息
     *
     * @param list 车辆信息信息集合
     * @return 结果
     */
    @Override
    @Transactional
    public boolean importData(List<XhCarInfo> list){
        SqlSession sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH, false);
        try {
            XhCarInfoMapper xhCarInfoMapper = sqlSession.getMapper(XhCarInfoMapper.class);
            list.forEach(item -> {
                item.setDeptId(getDeptId());
                if (this.lambdaQuery().eq(XhCarInfo::getCarNo,item.getCarNo())
                        .eq(XhCarInfo::getDeptId,item.getDeptId())
                        .eq(XhCarInfo::getDelFlag,XHConstant.DEL_FLAG_NORMAL).count() == 0) {
                    xhCarInfoMapper.insert(item);
                }
            });
            // 提交数据
            sqlSession.commit();
            sqlSession.rollback();
        } catch (Exception e) {
            sqlSession.rollback();
            return false;
        } finally {
            sqlSession.close();
        }
        return true;
    }

    /**
     * 根据车型ID查询车辆信息
     *
     * @param xhCarInfo 车辆信息信息集合
     * @return 结果
     */
    @Override
    public List<XhCarInfo> getCarListByCarType(XhCarInfo xhCarInfo) {
        //没有输入车型
        if (xhCarInfo.getCarType() == null){
            return Collections.emptyList();
        }
        return this.lambdaQuery().eq(XhCarInfo::getCarType,xhCarInfo.getCarType()).list();
    }

    @Override
    public List<XhCarInfo> getCarListByDriverId(Long id) {
        return xhCarInfoMapper.getCarListByDriverId(id);
    }
}
